//
//  M_AddressDetailVC.swift
//  letuofu
//
//  Created by WH-JS on 2019/12/31.
//  Copyright © 2019 WH-JS. All rights reserved.
//

import UIKit
import MBProgressHUD

class M_AddressDetailVC: BaseViewControllerWithHeader {
    //定义一个闭包类型
    typealias succeedBlock = (_ vc : M_AddressDetailVC) -> Void
    //声明一个变量
    var callSucceedBlock: succeedBlock?
    //定义一个方法,方法的参数为和swiftBlock类型一致的闭包,并赋值给callBack
    func callSucceedBack(block: @escaping succeedBlock) {
        callSucceedBlock = block
    }
    
    var isadd = false
    var contactID = -1
    var dataAddress = [String:Any?]()
    var provinceCode = ""
    var cityCode = ""
    var districtCode = ""
    var townCode = ""
    let adCode = TextField()
    let receiptName = TextField()
    let mobile = TextField()
    let detailAddress = TextField()
    let postCode = TextField()
    let isDefault = UISwitch()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        setupUI()
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */
    

    func addAddress() {
        if !(mobile.text?.validateMobile() ?? false) {
            let popup = PopupBox(infoText: "手机号码不规范，请重新输入")
            popup.show(vc: UIViewController.topMostController() ?? self)
            return
        }
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "receiptName":receiptName.text ?? "",
                                    "mobile":mobile.text ?? "",
                                    "provinceCode":provinceCode,
                                    "cityCode":cityCode,
                                    "districtCode":districtCode,
                                    "townCode":townCode,
                                    "detailAddress":detailAddress.text ?? "",
                                    "postcode":postCode.text ?? "",
                                    "isDefault":isDefault.isOn]
        API.request(url: .M_AddContactAddress, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                self.popViewController()
                if self.callSucceedBlock != nil {
                    self.callSucceedBlock!(self)
                }
            }
            else {
                let popup = PopupSureBox(title: "地址保存失败", sureText: "确定")
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                    //确定执行
                }
            }
        }
    }
    
    func editAddress() {
        if !(mobile.text?.validateMobile() ?? false) {
            let popup = PopupBox(infoText: "手机号码不规范，请重新输入")
            popup.show(vc: UIViewController.topMostController() ?? self)
            return
        }
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "contactID":contactID,
                                    "receiptName":receiptName.text ?? "",
                                    "mobile":mobile.text ?? "",
                                    "provinceCode":provinceCode,
                                    "cityCode":cityCode,
                                    "districtCode":districtCode,
                                    "townCode":townCode,
                                    "detailAddress":detailAddress.text ?? "",
                                    "postcode":postCode.text ?? "",
                                    "isDefault":isDefault.isOn]
        API.request(url: .M_UpdateContactAddress, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                self.popViewController()
                if self.callSucceedBlock != nil {
                    self.callSucceedBlock!(self)
                }
            }
            else {
                let popup = PopupSureBox(title: "地址保存失败", sureText: "确定")
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                    //确定执行
                }
            }
        }
    }
    
    func delAddress() {
        MBProgressHUD.showOrIncrease()
        let params :[String:Any] = ["identityToken":LocalStorage.getString(forKey: USER_IDENTITYTOKEN) ?? "",
                                    "contactID":contactID]
        API.request(url: .M_DeleteContactAddress, params: params) { (result) in
            MBProgressHUD.hideOrDecrease()
            if result.success {
                self.popViewController()
                if self.callSucceedBlock != nil {
                    self.callSucceedBlock!(self)
                }
            }
            else {
                let popup = PopupSureBox(title: "删除失败", sureText: "确定")
                popup.show(vc: UIViewController.topMostController() ?? self)
                popup.onSureButtonClick = {
                    //确定执行
                }
            }
        }
    }
}


// MARK: UI
extension M_AddressDetailVC {
    func setupUI() {
        safeView.backgroundColor = .xF2F2F2
        headView.backgroundColor = .white
        var bgview = safeView.drawView { (make) in
            make.top.equalTo(headView.snp.bottom).offset(20)
            make.left.right.equalToSuperview()
            make.height.equalTo(50)
        }
        bgview.backgroundColor = .white
//        drawRightButton(imageName: "xiaoxi_4")
//        .addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        let newsButton = drawRightButton(imageName: "xiaoxi_4")
        newsButton.addTarget(self, action: #selector(_xiaoxiButtonClick(button:)), for: .touchUpInside)
        UnreadPointForNewsButton(button: newsButton, pointRadius: 3.5,
                                 pointOffset: .init(x: -9.5, y: 10),  color: .xE0551B)

        if isadd {
            headTitle.text = "新建收货地址"
        }
        else {
            headTitle.text = "编辑收货地址"
            drawRightButton(title: "删除")
            .addTarget(self, action: #selector(_shanchuButtonClick(button:)), for: .touchUpInside)
        }
        
        
        bgview.drawLabel(text: "收件人", fontSize: 12, textColor: .x333333) { (make) in
            make.top.equalToSuperview().offset(20)
            make.left.equalToSuperview().offset(10)
        }
        bgview.drawTextField(textField: receiptName, placeholder: "请填写收货人姓名", fontSize: 12, fontWeight: .regular, keyboardType: .default, returnKeyType: .done) { (make) in
            make.top.equalToSuperview().offset(20)
            make.left.equalToSuperview().offset(76)
            make.right.equalToSuperview().offset(-10)
        }
        //画横线
        var line = bgview.drawView { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        bgview = safeView.drawView { (make) in
            make.top.equalTo(bgview.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(50)
        }
        bgview.backgroundColor = .white
        bgview.drawLabel(text: "手机号码", fontSize: 12, textColor: .x333333) { (make) in
            make.top.equalToSuperview().offset(20)
            make.left.equalToSuperview().offset(10)
        }
        bgview.drawTextField(textField: mobile, placeholder: "请填写收货人手机号码", fontSize: 12, fontWeight: .regular, keyboardType: .phonePad, returnKeyType: .done) { (make) in
            make.top.equalToSuperview().offset(20)
            make.left.equalToSuperview().offset(76)
            make.right.equalToSuperview().offset(-10)
        }
        //画横线
        line = bgview.drawView { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        bgview = safeView.drawView { (make) in
            make.top.equalTo(bgview.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(50)
        }
        bgview.backgroundColor = .white
        bgview.drawLabel(text: "所在地区", fontSize: 12, textColor: .x333333) { (make) in
            make.top.equalToSuperview().offset(20)
            make.left.equalToSuperview().offset(10)
        }
        bgview.drawTextField(textField: adCode, placeholder: "点击选择", fontSize: 12, fontWeight: .regular, keyboardType: .default, returnKeyType: .done) { (make) in
            make.top.equalToSuperview().offset(20)
            make.left.equalToSuperview().offset(76)
            make.right.equalToSuperview().offset(-10)
        }
        adCode.isEnabled = false
        bgview.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(_onbgviewTap(tap:))))
        //画横线
        line = bgview.drawView { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        bgview = safeView.drawView { (make) in
            make.top.equalTo(bgview.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(50)
        }
        bgview.backgroundColor = .white
        bgview.drawLabel(text: "详细地址", fontSize: 12, textColor: .x333333) { (make) in
            make.top.equalToSuperview().offset(20)
            make.left.equalToSuperview().offset(10)
        }
        bgview.drawTextField(textField: detailAddress, placeholder: "街道、楼牌号", fontSize: 12, fontWeight: .regular, keyboardType: .default, returnKeyType: .done) { (make) in
            make.top.equalToSuperview().offset(20)
            make.left.equalToSuperview().offset(76)
            make.right.equalToSuperview().offset(-10)
        }
        //画横线
        line = bgview.drawView { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        bgview = safeView.drawView { (make) in
            make.top.equalTo(bgview.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(50)
        }
        bgview.backgroundColor = .white
        bgview.drawLabel(text: "邮政编码", fontSize: 12, textColor: .x333333) { (make) in
            make.top.equalToSuperview().offset(20)
            make.left.equalToSuperview().offset(10)
        }
        bgview.drawTextField(textField: postCode, placeholder: "输入邮政编码", fontSize: 12, fontWeight: .regular, keyboardType: .numberPad, returnKeyType: .done) { (make) in
            make.top.equalToSuperview().offset(20)
            make.left.equalToSuperview().offset(76)
            make.right.equalToSuperview().offset(-10)
        }
        //画横线
        line = bgview.drawView { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2
        
        bgview = safeView.drawView { (make) in
            make.top.equalTo(bgview.snp.bottom)
            make.left.right.equalToSuperview()
            make.height.equalTo(50)
        }
        bgview.backgroundColor = .white
        bgview.drawLabel(text: "设置为默认地址", fontSize: 12, textColor: .x333333) { (make) in
            make.top.equalToSuperview().offset(20)
            make.left.equalToSuperview().offset(10)
        }
        bgview.drawView(view: isDefault) { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-15)
        }
        isDefault.onTintColor = .xFC4C02
        
        //画横线
        line = bgview.drawView { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.bottom.equalToSuperview()
            make.height.equalTo(1)
        }
        line.backgroundColor = .xF2F2F2

        let btn = safeView.drawButton(title: "保存", titleColor: .white, fontSize: 15) { (make) in
            make.top.equalTo(bgview.snp.bottom).offset(20)
            make.centerX.equalToSuperview()
            make.left.equalToSuperview().offset(30)
            make.right.equalToSuperview().offset(-30)
            make.height.equalTo(35)
        }
        btn.backgroundColor = .xFC4C02
        btn.layer.cornerRadius = 7
        btn.addTarget(self, action: #selector(_saveButtonClick(button:)), for: .touchUpInside)
        
        initKeyboardObserver()
        fillAccessoryToolBar()
    }
}

// MARK: event & action
extension M_AddressDetailVC {
    @objc func _xiaoxiButtonClick(button: Button) {
        let vc = M_NewsListVC()
        pushViewController(vc)
    }
    
    @objc func _shanchuButtonClick(button: Button) {
        delAddress()
    }
    
    @objc func _saveButtonClick(button: Button) {
        UIApplication.shared.keyWindow?.endEditing(true)
        if isadd {
            addAddress()
        }
        else {
            editAddress()
        }
        
    }
    
    @objc func _onbgviewTap(tap:UITapGestureRecognizer){
        UIApplication.shared.keyWindow?.endEditing(true)
        let view = M_AddressSelView()
        self.safeView.drawView(view: view) { (make) in
            make.left.right.top.bottom.equalToSuperview()
        }
        view.backgroundColor = .init(white: 0, alpha: 0.5)
        view.callSelBlock(block: { (v) in
            self.provinceCode = v.provinceCode.getString("provinceID") ?? ""
            self.cityCode = v.cityCode.getString("cityID") ?? ""
            self.districtCode = v.districtCode.getString("districtID") ?? ""
            self.townCode = v.townCode.getString("townID") ?? ""
            
            var ad = v.provinceCode.getString("provinceName") ?? ""
            ad += " "
            ad += v.cityCode.getString("cityName") ?? ""
            ad += " "
            ad += v.districtCode.getString("districtName") ?? ""
            ad += " "
            ad += v.townCode.getString("townName") ?? ""
            self.adCode.text = ad
        })
    }
}
